package com.xsh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xsh.constant.Constant;
import com.xsh.mapper.UserMapper;
import com.xsh.pojo.User;
import com.xsh.service.UserService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public PageInfo<User> findByPageInfo(String order, Integer limit, Integer offset) {
        Integer pageNum = (offset / limit) + 1;
        PageHelper.startPage(pageNum, limit);
        return new PageInfo<>(userMapper.selectAll(order));
    }

    @Override
    public void regist(User user) {
        String salt = UUID.randomUUID().toString();
        user.setSalt(salt);
        String password = new Sha256Hash(user.getPassword(), salt, Constant.COUNT).toBase64();
        user.setPassword(password);
        userMapper.insert(user);
        for (Integer roleId : user.getRoles()) {
            userMapper.insertUserRole(user.getUserId(), roleId);
        }
    }

    @Override
    public User findByUserId(Integer userId) {
        return userMapper.selectByUserId(userId);
    }

    @Override
    public void updateUser(User user) {
        userMapper.update(user);
        userMapper.deleteUserRoleByUserId(user.getUserId());
        for (Integer roleId : user.getRoles()) {
            userMapper.insertUserRole(user.getUserId(), roleId);
        }
    }

    @Override
    public void deleteUser(Integer userId) {
        userMapper.deleteByUserId(userId);
    }
}
